import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { Route, withRouter } from 'react-router-dom';
import { toJS } from 'mobx';
import { Button, Icon, Modal, Tools, Tag } from 'weaver-mobile';
import { Form, RouteLayout } from 'weaver-mobile-page';

import { TitleUtil, colorRgb } from '../../util';
import Api from '../../apis/setting';

import TableList from './tableList';

const alert = Modal.alert;
const { getLabel } = Tools;
const noop = () => { }

@inject('labelManageStore')
@withRouter
@observer
export default class LabelManage extends Component {

  componentDidMount() {
    const { labelManageStore, title, path } = this.props;
    window.isUmount = false;
    this.modal = null;
    labelManageStore.init(path);
    Api.getEmailLabelCondition().then(res => {
      const { conditioninfo } = res;
      labelManageStore.setState({ condition: conditioninfo });
      labelManageStore.form.initForm(conditioninfo, `${labelManageStore.layout.path}/form`);
    });
    TitleUtil.setTitle(title);
  }

  componentWillUnmount() {
    const { refreshList } = this.props;
    window.isUmount = true;
    if (refreshList) {
      refreshList();
    }
    TitleUtil.resetEmElement();
    if (this.modal && typeof this.modal.close === 'function') {
      this.modal.close();
    }
  }

  doEdit = (id) => {
		const { history, labelManageStore, labelManageStore: { layout, form } } = this.props;
    if (id) {
      Api.getMailLabelBean({ id }).then(res => {
        const { status, emailLabelBean } = res;
        if (Number(status)) {
          labelManageStore.setState({ labelId: id });
          let fields = {};
          Object.keys(emailLabelBean).forEach(domkey => {
            fields = { ...fields, [domkey]: { value: emailLabelBean[domkey] } };
					});
          setTimeout(() => {
						form.updateFields(fields);
					}, 200);
        }
      });
    } else {
      labelManageStore.setState({ labelId: '' });
      form.resetFields();
    }
    history.push(layout.path);
  }

  doClearLabel = (id) => {
    this.modal = alert(getLabel('384431', '确定所有邮件都取消该标签标记吗？'), '', [
      { text: getLabel('31129', '取消') },
      { text: getLabel('826', '确定'), onPress: () => {
        const { labelManageStore } = this.props;
        labelManageStore.handleOperation({
          id,
          operation: 'clear',
        });
      }},
    ]);
  }

  doDel = (id) => {
    this.modal = alert(getLabel('15097', '确定要删除吗？'), '', [
      { text: getLabel('31129', '取消') },
      { text: getLabel('826', '确定'), onPress: () => {
        const { labelManageStore } = this.props;
        labelManageStore.handleOperation({
          id,
          operation: 'del',
        });
      }},
    ]);
  }

  handleSubmit = () => {
    const { labelManageStore, labelManageStore: { labelId, form }, history } = this.props;
    const { pass } = form.doValidate();
    if (pass) {
      labelManageStore.handleOperation({
        ...form.formParams,
        id: labelId,
        operation: labelId ? 'edit' : 'add',
      }, () => {
        form.resetFields();
        history.go(-1);
      });
    }
  }

  renderTitle = (data) => {
    const background = data.color;
    const rgb = colorRgb(data.color);
    const gray = (rgb[0] + rgb[1] + rgb[2]) / 3;
    const color = gray > 127 ? '#000' : '#fff';
    return (
      <Tag style={{ background, color }}>
        {data.name}
      </Tag>
    );
  }

  renderOps = (o, check, data) => {
    const { randomFieldId } = data;
    let handler = noop;
    let icon = '';
    if (o.index * 1 === 0) {
      handler = this.doEdit;
      icon = 'bianji';
    } else if (o.index * 1 === 1) {
      handler = this.doClearLabel;
      icon = 'mail-clear';
    } else if (o.index * 1 === 2) {
      handler = this.doDel;
      icon = 'delete';
    }
    return (
      <span
        onClick={() => handler(randomFieldId)}
        key={o.index}
        style={{ marginRight: 5 }}
      >
        {icon && <Icon type={icon}/>}
        {o.text}
      </span>
    );
  }

  getFields = () => {
    const { labelManageStore: { form } } = this.props;
    const { conditioninfo, isInit } = form;
		const fields = [];
    if (isInit) {
      toJS(conditioninfo).forEach((group) => {
        group.items.forEach((field) => {
          fields.push(<Form.Item
            key={field.domkey.join('__')}
            form={form}
            fieldConfig={field}
            onChange={form.onChange}
          />);
        });
      });
    }
    return fields;
  }

  render() {
    const { labelManageStore: { layout, tableListStore } } = this.props;
    return (
      <div className="label-manage">
        <Button className="btn-add" icon="open" onClick={() => this.doEdit()}>{getLabel('83263', '新建标签')}</Button>
        <TableList store={tableListStore} renderTitle={this.renderTitle} renderOps={this.renderOps}/>
        {layout && <Route
          key={layout.id}
          path={layout.path}
          render={() => (
            <RouteLayout>
              <div key="addMailLabel" className="wm-route-layout route-layout-form" >
                {this.getFields()}
                <div className="btn-group">
                  <Button type="primary" onClick={this.handleSubmit}>{getLabel('826', '确定')}</Button>
                </div>
              </div>
            </RouteLayout>
          )}
        />}
      </div>
    );
  }
}
